<template>
  <view>
    <cover-view style="z-index: 0;">
      <canvas
        canvas-id="canvas"
        class="canvas"
        :disable-scroll="true"
        @touchstart="uploadScaleStart"
        @touchmove="uploadScaleMove"
        @touchend="uploadScaleEnd"
        style="z-index: 1;"
      ></canvas>
    </cover-view>
    <button @click="clearCanvas">清空画布</button>
    <!-- <button @click="previewCanvas" style="margin-top: 10rpx">预览结果</button> -->
  </view>
</template>

<script>
const plugin = requirePlugin("WechatSI");
export default {
  name: "DrawPanel",
  data() {
    return {
      drawing: {
        canvasName: "canvas",
        ctx: null, // 初始化为null
        canvasWidth: 0,
        canvasHeight: 0,
        transparent: 1,
        selectColor: "black",
        lineColor: "#1A1A1A",
        lineSize: 1.5,
        lineMin: 0.5,
        lineMax: 4,
        pressure: 1,
        smoothness: 60,
        currentPoint: {},
        currentLine: [],
        firstTouch: true,
        radius: 1,
        cutArea: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
        },
        bethelPoint: [],
        lastPoint: 0,
        chirography: [],
        currentChirography: {},
        linePrack: [],
      },
    };
  },
  mounted() {
    console.log("DrawPanel mounted");
    // 确保查询上下文绑定到当前组件实例
    const query = wx.createSelectorQuery().in(this);
    query
      .select(".canvas")
      .boundingClientRect((rect) => {
        if (rect) {
          console.log(rect, "canvas rect");
          this.drawing.canvasWidth = rect.width;
          this.drawing.canvasHeight = rect.height;

          // 初始化ctx对象
          this.drawing.ctx = wx.createCanvasContext(
            this.drawing.canvasName,
            this
          );

          // 设置canvas背景
          this.setCanvasBg("white");
        } else {
          console.warn("Canvas rect is undefined.");
        }
      })
      .exec();
  },
  methods: {
    uploadScaleStart(e) {
      if (!this.drawing.ctx) {
        console.warn("Canvas context is not initialized.");
        return;
      }
      if (e.type != "touchstart") return false;
      console.log("Start");
      let ctx = this.drawing.ctx;
      ctx.setFillStyle(this.drawing.lineColor); // 初始线条设置颜色
      ctx.setGlobalAlpha(this.drawing.transparent); // 设置半透明
      let currentPoint = {
        x: e.touches[0].x,
        y: e.touches[0].y,
      };
      let currentLine = this.drawing.currentLine;
      currentLine.unshift({
        time: new Date().getTime(),
        dis: 0,
        x: currentPoint.x,
        y: currentPoint.y,
      });
      this.drawing.currentPoint = currentPoint;
      // currentLine
      if (this.drawing.firstTouch) {
        this.drawing.cutArea = {
          top: currentPoint.y,
          right: currentPoint.x,
          bottom: currentPoint.y,
          left: currentPoint.x,
        };
        this.drawing.firstTouch = false;
      }
      this.pointToLine(currentLine);
    },
    uploadScaleMove(e) {
      if (!this.drawing.ctx) {
        console.warn("Canvas context is not initialized.");
        return;
      }
      if (e.type != "touchmove") return false;
      console.log("Move");
      if (e.cancelable) {
        // 判断默认行为是否已经被禁用
        if (!e.defaultPrevented) {
          e.preventDefault();
        }
      }
      let point = {
        x: e.touches[0].x,
        y: e.touches[0].y,
      };

      //测试裁剪
      if (point.y < this.drawing.cutArea.top) {
        this.drawing.cutArea.top = point.y;
      }
      if (point.y < 0) this.drawing.cutArea.top = 0;

      if (point.x > this.drawing.cutArea.right) {
        this.drawing.cutArea.right = point.x;
      }
      if (this.drawing.canvasWidth - point.x <= 0) {
        this.drawing.cutArea.right = this.drawing.canvasWidth;
      }
      if (point.y > this.drawing.cutArea.bottom) {
        this.drawing.cutArea.bottom = point.y;
      }
      if (this.drawing.canvasHeight - point.y <= 0) {
        this.drawing.cutArea.bottom = this.drawing.canvasHeight;
      }
      if (point.x < this.drawing.cutArea.left) {
        this.drawing.cutArea.left = point.x;
      }
      if (point.x < 0) this.drawing.cutArea.left = 0;

      this.drawing.lastPoint = this.drawing.currentPoint;
      this.drawing.currentPoint = point;

      let currentLine = this.drawing.currentLine;
      currentLine.unshift({
        time: new Date().getTime(),
        dis: this.distance(this.drawing.currentPoint, this.drawing.lastPoint),
        x: point.x,
        y: point.y,
      });

      this.pointToLine(currentLine);
    },
    uploadScaleEnd(e) {
      if (!this.drawing.ctx) {
        console.warn("Canvas context is not initialized.");
        return;
      }
      if (e.type != "touchend") return 0;
      console.log("End");
      let point = {
        x: e.changedTouches[0].x,
        y: e.changedTouches[0].y,
      };
      this.drawing.lastPoint = this.drawing.currentPoint;
      this.drawing.currentPoint = point;

      let currentLine = this.drawing.currentLine;
      currentLine.unshift({
        time: new Date().getTime(),
        dis: this.distance(this.drawing.currentPoint, this.drawing.lastPoint),
        x: point.x,
        y: point.y,
      });

      if (currentLine.length > 2) {
        var info =
          (currentLine[0].time - currentLine[currentLine.length - 1].time) /
          currentLine.length;
        //$("#info").text(info.toFixed(2));
      }
      //一笔结束，保存笔迹的坐标点，清空，当前笔迹
      //增加判断是否在手写区域；
      this.pointToLine(currentLine);
      var currentChirography = {
        lineSize: this.drawing.lineSize,
        lineColor: this.drawing.lineColor,
      };
      var chirography = this.drawing.chirography;
      chirography.unshift(currentChirography);
      this.drawing.chirography = chirography;

      var linePrack = this.drawing.linePrack;
      linePrack.unshift(this.drawing.currentLine);
      this.drawing.linePrack = linePrack;
      this.drawing.currentLine = [];
    },
    clearCanvas() {
      if (!this.drawing.ctx) {
        console.warn("Canvas context is not initialized.");
        return;
      }
      if (this.drawing.ctx) {
        this.drawing.ctx.clearRect(
          0,
          0,
          this.drawing.canvasWidth,
          this.drawing.canvasHeight
        ); // Clear canvas
        this.drawing.ctx.draw(); // Redraw to ensure the canvas clears
        // 设置canvas背景
        this.setCanvasBg("white");
        // 清空所有保存的线条
        this.drawing.linePrack = [];
      } else {
        console.warn("Canvas or context is not initialized yet.");
      }
    },
    // previewCanvas函数存在问题，后续再调整
    previewCanvas() {
      if (!this.drawing.ctx) {
        console.warn("Canvas context is not initialized.");
        return;
      }
      // 确保所有绘制操作已完成
      this.drawing.ctx.draw(true, () => {
        wx.canvasToTempFilePath({
          canvasId: "canvas",
          fileType: "png",
          quality: 1, // 图片质量
          success: (res) => {
            console.log(res.tempFilePath, "canvas生成图片地址");
            wx.previewImage({
              urls: [res.tempFilePath], // 预览图片 数组
            });
          },
          fail: (err) => {
            console.error("canvasToTempFilePath fail", err);
            wx.showToast({
              title: "导出图片失败，请稍后重试",
              icon: "none",
            });
          },
        });
      });
    },
    pointToLine(line) {
      this.calcBethelLine(line);
      return;
    },
    //计算插值的方式；
    calcBethelLine(line) {
      if (line.length <= 1) {
        line[0].r = this.drawing.radius;
        return;
      }
      let x0,
        x1,
        x2,
        y0,
        y1,
        y2,
        r0,
        r1,
        r2,
        len,
        lastRadius,
        dis = 0,
        time = 0,
        curveValue = 0.5;
      if (line.length <= 2) {
        x0 = line[1].x;
        y0 = line[1].y;
        x2 = line[1].x + (line[0].x - line[1].x) * curveValue;
        y2 = line[1].y + (line[0].y - line[1].y) * curveValue;
        //x2 = line[1].x;
        //y2 = line[1].y;
        x1 = x0 + (x2 - x0) * curveValue;
        y1 = y0 + (y2 - y0) * curveValue;
      } else {
        x0 = line[2].x + (line[1].x - line[2].x) * curveValue;
        y0 = line[2].y + (line[1].y - line[2].y) * curveValue;
        x1 = line[1].x;
        y1 = line[1].y;
        x2 = x1 + (line[0].x - x1) * curveValue;
        y2 = y1 + (line[0].y - y1) * curveValue;
      }
      //从计算公式看，三个点分别是(x0,y0),(x1,y1),(x2,y2) ；(x1,y1)这个是控制点，控制点不会落在曲线上；实际上，这个点还会手写获取的实际点，却落在曲线上
      len = this.distance(
        {
          x: x2,
          y: y2,
        },
        {
          x: x0,
          y: y0,
        }
      );
      lastRadius = this.drawing.radius;
      for (let n = 0; n < line.length - 1; n++) {
        dis += line[n].dis;
        time += line[n].time - line[n + 1].time;
        if (dis > this.drawing.smoothness) break;
      }

      this.drawing.radius =
        Math.min(
          (time / len) * this.drawing.pressure + this.drawing.lineMin,
          this.drawing.lineMax
        ) * this.drawing.lineSize;
      line[0].r = this.drawing.radius;
      //计算笔迹半径；
      if (line.length <= 2) {
        r0 = (lastRadius + this.drawing.radius) / 2;
        r1 = r0;
        r2 = r1;
        //return;
      } else {
        r0 = (line[2].r + line[1].r) / 2;
        r1 = line[1].r;
        r2 = (line[1].r + line[0].r) / 2;
      }
      let n = 5;
      let point = [];
      for (let i = 0; i < n; i++) {
        let t = i / (n - 1);
        let x = (1 - t) * (1 - t) * x0 + 2 * t * (1 - t) * x1 + t * t * x2;
        let y = (1 - t) * (1 - t) * y0 + 2 * t * (1 - t) * y1 + t * t * y2;
        let r = lastRadius + ((this.drawing.radius - lastRadius) / n) * i;
        point.push({
          x: x,
          y: y,
          r: r,
        });
        if (point.length == 3) {
          let a = this.ctaCalc(
            point[0].x,
            point[0].y,
            point[0].r,
            point[1].x,
            point[1].y,
            point[1].r,
            point[2].x,
            point[2].y,
            point[2].r
          );
          a[0].color = this.drawing.lineColor;
          this.bethelDraw(a, 1);
          point = [
            {
              x: x,
              y: y,
              r: r,
            },
          ];
        }
      }
      this.drawing.currentLine = line;
    },
    //求两点之间距离
    distance(a, b) {
      let x = b.x - a.x;
      let y = b.y - a.y;
      return Math.sqrt(x * x + y * y);
    },
    ctaCalc(x0, y0, r0, x1, y1, r1, x2, y2, r2) {
      let a = [],
        vx01,
        vy01,
        norm,
        n_x0,
        n_y0,
        vx21,
        vy21,
        n_x2,
        n_y2;
      vx01 = x1 - x0;
      vy01 = y1 - y0;
      norm = Math.sqrt(vx01 * vx01 + vy01 * vy01 + 0.0001) * 2;
      vx01 = (vx01 / norm) * r0;
      vy01 = (vy01 / norm) * r0;
      n_x0 = vy01;
      n_y0 = -vx01;
      vx21 = x1 - x2;
      vy21 = y1 - y2;
      norm = Math.sqrt(vx21 * vx21 + vy21 * vy21 + 0.0001) * 2;
      vx21 = (vx21 / norm) * r2;
      vy21 = (vy21 / norm) * r2;
      n_x2 = -vy21;
      n_y2 = vx21;
      a.push({
        mx: x0 + n_x0,
        my: y0 + n_y0,
        color: "#1A1A1A",
      });
      a.push({
        c1x: x1 + n_x0,
        c1y: y1 + n_y0,
        c2x: x1 + n_x2,
        c2y: y1 + n_y2,
        ex: x2 + n_x2,
        ey: y2 + n_y2,
      });
      a.push({
        c1x: x2 + n_x2 - vx21,
        c1y: y2 + n_y2 - vy21,
        c2x: x2 - n_x2 - vx21,
        c2y: y2 - n_y2 - vy21,
        ex: x2 - n_x2,
        ey: y2 - n_y2,
      });
      a.push({
        c1x: x1 - n_x2,
        c1y: y1 - n_y2,
        c2x: x1 - n_x0,
        c2y: y1 - n_y0,
        ex: x0 - n_x0,
        ey: y0 - n_y0,
      });
      a.push({
        c1x: x0 - n_x0 - vx01,
        c1y: y0 - n_y0 - vy01,
        c2x: x0 + n_x0 - vx01,
        c2y: y0 + n_y0 - vy01,
        ex: x0 + n_x0,
        ey: y0 + n_y0,
      });
      a[0].mx = a[0].mx.toFixed(1);
      a[0].mx = parseFloat(a[0].mx);
      a[0].my = a[0].my.toFixed(1);
      a[0].my = parseFloat(a[0].my);
      for (let i = 1; i < a.length; i++) {
        a[i].c1x = a[i].c1x.toFixed(1);
        a[i].c1x = parseFloat(a[i].c1x);
        a[i].c1y = a[i].c1y.toFixed(1);
        a[i].c1y = parseFloat(a[i].c1y);
        a[i].c2x = a[i].c2x.toFixed(1);
        a[i].c2x = parseFloat(a[i].c2x);
        a[i].c2y = a[i].c2y.toFixed(1);
        a[i].c2y = parseFloat(a[i].c2y);
        a[i].ex = a[i].ex.toFixed(1);
        a[i].ex = parseFloat(a[i].ex);
        a[i].ey = a[i].ey.toFixed(1);
        a[i].ey = parseFloat(a[i].ey);
      }
      return a;
    },
    bethelDraw(point, is_fill, color) {
      let ctx = this.drawing.ctx;
      ctx.beginPath();
      ctx.moveTo(point[0].mx, point[0].my);
      if (undefined != color) {
        ctx.setFillStyle(color);
        ctx.setStrokeStyle(color);
      } else {
        ctx.setFillStyle(point[0].color);
        ctx.setStrokeStyle(point[0].color);
      }
      for (let i = 1; i < point.length; i++) {
        ctx.bezierCurveTo(
          point[i].c1x,
          point[i].c1y,
          point[i].c2x,
          point[i].c2y,
          point[i].ex,
          point[i].ey
        );
      }
      ctx.stroke();
      if (undefined != is_fill) {
        ctx.fill(); //填充图形 ( 后绘制的图形会覆盖前面的图形, 绘制时注意先后顺序 )
      }
      ctx.draw(true);
    },
    /* 将canvas背景设置为 白底，不设置  导出的canvas的背景默认为黑色 */
    setCanvasBg(color) {
      if (!this.drawing.ctx) {
        console.warn("Canvas context is not initialized.");
        return;
      }
      // rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
      this.drawing.ctx.rect(
        0,
        0,
        this.drawing.canvasWidth,
        this.drawing.canvasHeight
      );
      this.drawing.ctx.setFillStyle(color);
      this.drawing.ctx.fill(); // 设置填充
      this.drawing.ctx.draw(); // 开始绘制
    },
  },
};
</script>

<style scoped>
.canvas {
  width: 100%;
  height: 300rpx;
  border: 1px solid #ccc;
}
</style>